﻿using System;
using System.IO;
using System.Text;
using System.Net.Mail;
using System.Net;
using System.Linq;
using System.Text.RegularExpressions;
using System.Configuration;
using System.Collections.Generic;

namespace ZP.Common
{
    public class ZPEmailHelper
    {
        public static string zp_email_host = ConfigurationManager.AppSettings["zp_email_host"];
        public static string zp_email_username = ConfigurationManager.AppSettings["zp_email_username"];
        public static string zp_email_password = ConfigurationManager.AppSettings["zp_email_password"];

        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="emailAddressList">收件人地址集合</param>
        /// <param name="Subject">邮件标题</param>
        /// <param name="Body">邮件体(可以为html)</param>
        public static bool SendEmail(string Subject, string Body, List<string> emailAddressList)
        {
            bool send = false;
#if DEBUG
            zp_email_host = "smtp.163.com";
            zp_email_username = "mystery_tao@163.com";
            zp_email_password = "GQWOTFABQHOJIBPE";//网易授权码//GQWOTFABQHOJIBPE
#endif
            try
            {
                System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
                client.Host = zp_email_host;//使用163的SMTP服务器发送邮件
                client.UseDefaultCredentials = true;
                client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
                client.Credentials = new System.Net.NetworkCredential(zp_email_username, zp_email_password);//163的SMTP服务器需要用163邮箱的用户名和smtp授权码作认证，如果没有需要去163申请个,
                //这里假定你已经拥有了一个163邮箱的账户，用户名为abc，密码为*******
                System.Net.Mail.MailMessage Message = new System.Net.Mail.MailMessage();
                Message.From = new System.Net.Mail.MailAddress(zp_email_username);//这里需要注意，163似乎有规定发信人的邮箱地址必须是163的，而且发信人的邮箱用户名必须和上面SMTP服务器认证时的用户名相同
                //因为上面用的用户名abc作SMTP服务器认证，所以这里发信人的邮箱地址也应该写为abc@163.com
                if (emailAddressList.Count == 0)
                {
                    //Logger.WriteLog("SendEmail emailAddress and emailAddressList is emtpy.");
                    return false;
                }
                if (emailAddressList != null && emailAddressList.Count > 0)
                    foreach (string email in emailAddressList)
                        Message.To.Add(email);

                //Message.To.Add("123456@gmail.com");//将邮件发送给Gmail
                //Message.To.Add("123456@qq.com");//将邮件发送给QQ邮箱
                Message.Subject = Subject;
                Message.Body = Body;
                Message.SubjectEncoding = System.Text.Encoding.UTF8;
                Message.BodyEncoding = System.Text.Encoding.UTF8;
                Message.Priority = System.Net.Mail.MailPriority.High;
                Message.IsBodyHtml = true;　　//可以为html

                client.Send(Message);
                send = true;
            }
            catch (Exception ex)
            {
                //Logger.WriteLog("SendEmail error:" + ex.Message);
                //Logger.WriteLog("SendEmail error:" + ex.StackTrace);
                /*string path = Server.MapPath("~") + "\\mail.txt";
                if (!System.IO.File.Exists(path))
                {
                    FileStream fs1 = new FileStream(path, FileMode.Create, FileAccess.Write);//创建写入文件 
                    StreamWriter sw = new StreamWriter(fs1);
                    sw.WriteLine(DateTime.Now.ToString() + " ;Source:" + ex.Source + " ;HelpLink:" + ex.HelpLink + " ;Message:" + ex.Message);//开始写入值
                    sw.Close();
                    fs1.Close();
                }
                else
                {
                    StreamWriter sr = System.IO.File.AppendText(path);
                    sr.WriteLine(DateTime.Now.ToString() + " ;Source:" + ex.Source + " ;HelpLink:" + ex.HelpLink + " ;Message:" + ex.Message);//追加写入值
                    sr.Close();
                }*/
            }
            return send;
        }

        /// <summary>
        ///生成制定位数的随机码（数字）
        /// </summary>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string GenerateRandomCode(int length)
        {
            var result = new StringBuilder();
            for (var i = 0; i < length; i++)
            {
                var r = new Random(Guid.NewGuid().GetHashCode());
                result.Append(r.Next(0, 10));
            }
            return result.ToString();
        }
    }


    public class MailSmtp
    {
        /// <summary>
        /// 设置邮件编码类型
        /// </summary>
        /// <param name="contentEncoding"></param>
        public void SetEncoding(Encoding contentEncoding)
        {
            this._encoding = contentEncoding;

        }
        /// <summary>
        ///设置邮件正文是否为 Html 格式
        /// </summary>
        /// <param name="isHtml"></param>
        public void SetIsHtml(bool isHtml)
        {
            this._isHtml = isHtml;
        }
        /// <summary>
        /// 抄送
        /// </summary>
        /// <param name="cc"></param>
        public void SetCC(params string[] cc)
        {
            this._cc = cc;
        }
        /// <summary>
        /// 暗送
        /// </summary>
        /// <param name="cc"></param>
        public void SetBC(params string[] bc)
        {
            this._bcc = bc;
        }
        /// <summary>
        /// 是否ssl加密
        /// </summary>
        /// <param name="isSSL"></param>
        public void SetIsSSL(bool isSSL)
        {
            this._smtp.EnableSsl = isSSL;
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="host"></param>
        /// <param name="username">邮件账号</param>
        /// <param name="password">密码</param>
        public MailSmtp(string host, string username, string password)
        {
            this._smtp.Host = host;
            this._smtp.Port = 0x19;
            this._smtp.EnableSsl = false;
            this._isHtml = true;
            this._encoding = Encoding.UTF8;
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                this._smtp.UseDefaultCredentials = false;
            }
            else
            {
                this._smtp.Credentials = new NetworkCredential(username, password);
            }
        }

        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="from">发件人邮件地址</param>
        /// <param name="sender">发件人显示名称</param>
        /// <param name="to">收件人地址</param>
        /// <param name="subject">邮件标题</param>
        /// <param name="body">邮件正文</param>
        /// <param name="file">附件地址数组</param>
        /// <returns>bool 是否成功 </returns>
        public bool Send(string from, string sender, string to, string subject, string body, params string[] file)
        {
            return Send(from, sender, new string[] { to }, subject, body, file);
        }

        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="from">发件人邮件地址</param>
        /// <param name="sender">发件人显示名称</param>
        /// <param name="to">收件人地址</param>
        /// <param name="subject">邮件标题</param>
        /// <param name="body">邮件正文</param>
        /// <param name="file">附件地址数组</param>
        /// <returns>bool 是否成功 </returns>
        public bool Send(string from, string sender, string[] to, string subject, string body, params string[] file)
        {
            string mailReg = @"^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$";
            if (to == null)
            {
                throw new ArgumentNullException("MailSmtp.Send.to");
            }

            if (to.Any(oit => !Regex.IsMatch(oit + "", mailReg)))
            {
                this.Result = "收件人地址不合法";
                return false;
            }
            if (_bcc != null && _bcc.Length > 0)
            {
                if (_bcc.Any(oit => !Regex.IsMatch(oit + "", mailReg)))
                {
                    this.Result = "暗送人地址不合法";
                    return false;
                }
            }
            if (_cc != null && _cc.Length > 0)
            {
                if (_cc.Any(oit => !Regex.IsMatch(oit + "", mailReg)))
                {
                    this.Result = "抄送人地址不合法";
                    return false;
                }
            }
            MailMessage message = new MailMessage();

            if (file != null)
            {
                // 创建一个附件对象
                foreach (var r in file)
                {
                    Attachment objMailAttachment;
                    objMailAttachment = new Attachment(r);//发送邮件的附件
                    message.Attachments.Add(objMailAttachment);
                }
            }

            message.From = new MailAddress(from, sender);
            message.Subject = subject;
            message.SubjectEncoding = this._encoding;
            message.Body = body;
            message.BodyEncoding = this._encoding;
            message.IsBodyHtml = this._isHtml;
            message.Priority = MailPriority.Normal;
            foreach (string str in to)
            {
                message.To.Add(str);
            }
            if (this._bcc != null && this._bcc.Length > 0)
            {
                foreach (string b in this._bcc)
                {
                    message.Bcc.Add(b);
                }
            }
            if (this._cc != null && this._cc.Length > 0)
            {
                foreach (string c in this._cc)
                {
                    message.CC.Add(c);
                }
            }

            try
            {
                this._smtp.Send(message);
                return true;
            }
            catch (Exception ex)
            {

                Console.WriteLine(ex.Message);
            }

            return false;
        }

        private SmtpClient _smtp = new SmtpClient();
        private Encoding _encoding { get; set; }
        private bool _isHtml { get; set; }
        private string[] _cc { get; set; }
        private string[] _bcc { get; set; }
        /// <summary>
        /// 获取发送结果，成功则为空
        /// </summary>
        public string Result { get; private set; }
    }
}